import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useNotificationStore = defineStore('notification', () => {
  // 未读消息数量
  const unreadCount = ref(0)
  
  // 通知列表（可选，用于缓存）
  const notifications = ref([])
  
  // localStorage 配置
  const STORAGE_KEY = 'notification_unread_count'
  
  // 从 localStorage 加载未读数
  const loadUnreadCount = () => {
    try {
      const stored = localStorage.getItem(STORAGE_KEY)
      if (stored) {
        unreadCount.value = parseInt(stored, 10) || 0
      }
    } catch (error) {
      console.error('[NotificationStore] 加载未读数失败:', error)
    }
  }
  
  // 保存未读数到 localStorage
  const saveUnreadCount = () => {
    try {
      localStorage.setItem(STORAGE_KEY, String(unreadCount.value))
    } catch (error) {
      console.error('[NotificationStore] 保存未读数失败:', error)
    }
  }
  
  // 增加未读数
  const incrementUnread = () => {
    unreadCount.value++
    saveUnreadCount()
  }
  
  // 设置未读数
  const setUnreadCount = (count) => {
    unreadCount.value = Math.max(0, count)
    saveUnreadCount()
  }
  
  // 清空未读数
  const clearUnread = () => {
    unreadCount.value = 0
    saveUnreadCount()
  }
  
  // 减少未读数
  const decrementUnread = () => {
    if (unreadCount.value > 0) {
      unreadCount.value--
      saveUnreadCount()
    }
  }
  
  // 是否有未读消息
  const hasUnread = computed(() => unreadCount.value > 0)
  
  // 格式化未读数显示（99+）
  const unreadDisplay = computed(() => {
    return unreadCount.value > 99 ? '99+' : String(unreadCount.value)
  })
  
  // 初始化时加载未读数
  loadUnreadCount()
  
  return {
    unreadCount,
    notifications,
    hasUnread,
    unreadDisplay,
    incrementUnread,
    setUnreadCount,
    clearUnread,
    decrementUnread,
    loadUnreadCount,
    saveUnreadCount
  }
})


